# DataDB.gd  —— Godot 4.4
extends Node
signal reloaded

const PATHS := {
	"skills":       "res://data/skills.json",
	"statuses":     "res://data/statuses.json",
	"equip_rules":  "res://data/equipment_rules.json",
	"items":        "res://data/items.json",
	"enemies":      "res://data/enemies.json",
	"drops":        "res://data/drop_table.json"
}

var skills: Dictionary = {}
var statuses: Dictionary = {}
var equip_rules: Dictionary = {}
var items: Dictionary = {}
var enemies: Dictionary = {}
var drops: Dictionary = {}

var skill_by_id: Dictionary = {}
var skill_order: Array[String] = []

# 把 JSON 里的状态 id 映射到你的枚举顺序
# 0=poison, 1=burn, 2=stun, 3=shield
var status_index: Dictionary = { "poison":0, "burn":1, "stun":2, "shield":3 }

func _ready():
	reload()

func _load_json(path:String) -> Dictionary:
	if not ResourceLoader.exists(path):
		return {}
	var s := FileAccess.get_file_as_string(path)
	var d = JSON.parse_string(s)
	if typeof(d) == TYPE_DICTIONARY:
		return d
	return {}

func reload():
	skills      = _load_json(PATHS["skills"])
	statuses    = _load_json(PATHS["statuses"])
	equip_rules = _load_json(PATHS["equip_rules"])
	items       = _load_json(PATHS["items"])
	enemies     = _load_json(PATHS["enemies"])
	drops       = _load_json(PATHS["drops"])

	# 索引化技能
	skill_by_id.clear()
	skill_order.clear()
	var arr:Array = skills.get("skills", [])
	for e in arr:
		var sid := String(e.get("id",""))
		if sid != "":
			skill_by_id[sid] = e
	var order:Array = skills.get("skill_order", [])
	if order.size() > 0:
		for x in order:
			var sid2 := String(x)
			if skill_by_id.has(sid2):
				skill_order.append(sid2)
	else:
		for k in skill_by_id.keys():
			skill_order.append(String(k))

	emit_signal("reloaded")

func get_skill(id:String) -> Dictionary:
	if skill_by_id.has(id):
		return skill_by_id[id]
	return {}

# 掉落一次（命中总概率后，按权重挑一项）
func get_drop_entry() -> Dictionary:
	var chance := int(drops.get("drop_chance_percent", 0))
	var entries:Array = drops.get("entries", [])
	var empty := {}
	if chance <= 0:
		return empty
	var r := randi() % 100 + 1
	if r > chance:
		return empty
	var total := 0
	for e in entries:
		total += int(e.get("weight", 0))
	if total <= 0:
		return empty
	var pick := randi() % total + 1
	var acc := 0
	for e2 in entries:
		acc += int(e2.get("weight", 0))
		if pick <= acc:
			return e2
	if entries.size() > 0:
		return entries.back()
	return empty
